import {defineStore} from 'pinia'

interface IRouter {
    fullPath?: string;
    hash?: string;
    href?: string;
    name?: string;
    path?: string;
    meta?: Object;
    params?: Object;
    query?: Object;
}

export const useRouterStore = defineStore('router', {
    state: () => {
        return {
            history: [],
            current: {
                fullPath: '',
                hash: '',
                href: '',
                name: '',
                path: '',
                meta: {},
                params: {},
                query: {},
            }
        }
    },
    getters: {
        getHistory(): Array<IRouter> {
            return this.history
        },
        getCurrent(): IRouter {
            return this.current
        }
    },
    actions: {
        pushHistory(res: IRouter): void {

            if (!res.meta.hasOwnProperty('history') || !res.meta.history) {
                return
            }

            let index: number = this.history.findIndex(item => item.path === res.path)

            if (index < 0) {
                this.history.push(res)
            }

            this.setCurrent(res)

        },
        setCurrent(res: IRouter): void {
            this.current = res
        },

        removeHistory(index:number) {

            let rIndex: number = index + 1;
            let lIndex: number = index - 1;

            if (this.history[rIndex]) {
                this.setCurrent(this.history[rIndex])
            } else {
                if (this.history[lIndex]) {
                    this.setCurrent(this.history[lIndex])
                }else{
                    this.setCurrent({})
                }
            }

            this.history.splice(index, 1)

        }

    },
    persist: true
})